(function() {
    //游戏的构造函数
    var that = null;
    function Game(map) {
        this.food = new Food()
        this.snake = new Snake()
        this.map = map
        that = this
    }
    //游戏初始化
    Game.prototype.init = function () {
         
        this.food.init(this.map)
        this.snake.init(this.map)
        this.snakeRun(this.food, this.map)
        this.bindKey()           
    }
    //游戏自动游戏
    Game.prototype.snakeRun = function () {
        var timeId = setInterval(function () {
            this.snake.init(this.map)
            this.snake.move(this.food,this.map)
            //横坐标最大值
            var maxX = map.offsetWidth/this.snake.width
            //纵坐标最大值
            var maxY = map.offsetHeight/this.snake.height
            //小蛇头部坐标
            var headX = this.snake.body[0].x
            var headY = this.snake.body[0].y
            if(headX < 0 || headX >= maxX ) {
                clearInterval(timeId)
                alert("game over")
            }
            if(headY <0 || headY >= maxY) {
                clearInterval(timeId)
                alert("game over")
            }
        }.bind(that), 150)
    }
    //用户按键调整小蛇方向
    Game.prototype.bindKey = function () {
        document.addEventListener("keydown", function (e) {
            switch (e.keyCode) {
                case 37 : this.snake.direction = "left" ; break;
                case 38 : this.snake.direction = "top" ; break;
                case 39 : this.snake.direction = "right" ; break;
                case 40 : this.snake.direction = "bottom" ; break;
            }
        }.bind(that), false)
    }

    window.Game = Game    
}());